package com.hxl.tech.gateway.auth.util;


import com.hxl.tech.gateway.auth.exception.AuthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

@Slf4j
public class RestTemplateUtil {

    public static RestTemplate getRestTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
        httpMessageConverters.stream().forEach(httpMessageConverter -> {
            if(httpMessageConverter instanceof StringHttpMessageConverter){
                StringHttpMessageConverter messageConverter = (StringHttpMessageConverter) httpMessageConverter;
                messageConverter.setDefaultCharset(Charset.forName("GBK"));
            }
        });
        return restTemplate;
    }

    public static <T> T send(String url, HttpMethod method, String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        ParameterizedTypeReference<T> type = new ParameterizedTypeReference <T>() {};
        HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
        RestTemplate restTemplate = getRestTemplate();

        ResponseEntity<T> responseEntity = restTemplate.exchange(url, method, requestEntity, type);
        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
            throw new AuthException("外部Http请求异常");
        }
        return responseEntity.getBody();
    }

    public static Object send(String url) {

        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("grant_type", "manager_token");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
        RestTemplate restTemplate = new RestTemplate();
        Object obj = restTemplate.postForObject(url, r, String.class);
        return obj;
    }

}